#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from QRServer.utility import phone_json
from models import*
from devices.models import Device
import json



def get_maintain_dic(num):
    '''获取维修记录'''
    theDevice = get_object_or_404(Device, num=num)
    info = {}
    i = 0
    for maintain in theDevice.maintain_set.all():
        info[repr(i)] = maintain.phone()
        i += 1
    return info


def maintain_dic_to_li(dic):
    li = []
    keys = list(dic)
    sorted(keys)
    for key in keys:
        li.append(dic[key])
    return li


def search(POST):
    result_info = {'result':[],'message':None}
    result = Device.objects.filter(
        name__contains=POST['name'],
        num__contains=POST['num'],
        location__contains=POST['location'],
    )

    for device in result:
        maintains = maintain_dic_to_li(get_maintain_dic(device.num))
        result_info['result'].append([
            device.num,
            device.name,
            maintains,
        ])

    length = len(result_info['result'])
    if length <= 10 and length:
        result_info['message'] = '搜索完成！共计'+str(length)+'个设备的维修记录。'
    elif length:
        result_info['message'] = '搜索完成！共计'+str(length)+'个设备的维修记录。建议通过增加搜索项来缩小结果范围。'
    else:
        result_info['message'] = '(T_T) 一条维修记录都没找到,扩大一下范围呗？'
    return result_info


@csrf_exempt
def phone(request):
    GETinfo = {'num': request.POST['num']}
    if request.POST['flag'] == '2':
        QRinfo = get_maintain_dic(request.POST['num'])
        return HttpResponse(phone_json(QRinfo, GETinfo))
    else:
        return Http404


@login_required
@csrf_exempt
def phone_maintain(request):
    '''这是测试用老师列表'''
    test_teacher_info = {
        'QRinfo':{
            'teacher':{
                '谭老师':0,
                '张老师':1,
                },
            },
        }
    if request.method=="POST":
        theDevice = get_object_or_404(Device, num=request.POST['id'])
        if request.POST['solved']=='True':
            theDevice.status = 0
        theDevice.maintain_set.create(
            malfunction=request.POST['malfunction'],
            solution=request.POST['solution'],
            head=request.POST['head'],
            repairman=request.user.get_username(),
        )
        success_info = 'Accepted!'
        return HttpResponse(success_info)
    else:
        return HttpResponse(json.dumps(test_teacher_info, ensure_ascii=False, cls=DjangoJSONEncoder))


@csrf_exempt
def maintain_search(request):
    message = "表格至少填写一项，支持模糊查询。只显示最近的6条维修记录，查看更多维修记录请联系管理员。"
    result = []

    if request.method=="POST":
        result_info = search(request.POST)
        '''result的格式是'''
        result = result_info['result']
        message = result_info['message']
        maintains = range(6)

    return render_to_response('maintain/maintain.html', locals(), context_instance=RequestContext(request))
